#include "config.h"

int cli_fd;

/**
 * 读取server转发过来的消息
 */
void* client_read(void* arg)
{
    int       cli_fd              = *(int*)arg;
    message_t mesg                = {};
    char      buffer[BUFFER_SIZE] = {};

    mesg.cli_msg = CLIENT_MSG_CREATE_ROOM;
    memset(buffer, 0, sizeof(buffer));
    memcpy(buffer, &mesg, sizeof(message_t));
    send(cli_fd, &buffer, sizeof(message_t), 0);

    // 接收数据
    for (;;) {
        memset(buffer, 0, sizeof(buffer));
        int recv_size = read(cli_fd, &buffer, sizeof(buffer));
        if (recv_size <= 0) {
            printf("已经与服务器断开链接\n");
            close(cli_fd);
            pthread_exit(NULL);
        }

        memcpy(&mesg, buffer, sizeof(buffer));
        printf("srv_msg=%d\n", mesg.srv_msg);
        printf("cli_msg=%d\n", mesg.cli_msg);
    }
}

/**
 * quit
 */
void sigint(int signum)
{
    close(cli_fd);
    printf("[system]断开\n");
    _exit(0);
}

int main()
{
    // 创建socket对象
    printf("创建socket对象...\n");
    cli_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (0 > cli_fd) {
        perror("socket");
        return -1;
    }

    // 准备通信地址(服务端)
    printf("准备通信地址...\n");
    struct sockaddr_in addr = {};
    addr.sin_family         = AF_INET;
    addr.sin_port           = htons(PORT);
    addr.sin_addr.s_addr    = inet_addr(SERVER_ADDR);   // 此处填写自己的ip地址
    socklen_t addrlen       = sizeof(addr);

    // 链接服务端
    printf("链接服务端口...\n");
    if (connect(cli_fd, (struct sockaddr*)&addr, addrlen)) {
        perror("connect");
        return -1;
    }

    printf("链接成功\n");

    // 链接成功，创建客户端
    pthread_t tid;
    pthread_create(&tid, NULL, client_read, &cli_fd);

    message_t mesg                = {};
    char      buffer[BUFFER_SIZE] = {};
    while (1) {
        int choice_cli = 0;
        int choice_srv = 0;
        int x      = 0;
        int y      = 0;
        printf("输入 cli_msg:");
        scanf("%d", &choice_cli);
        printf("输入 choice_srv:");
        scanf("%d", &choice_srv);
        if (choice_cli == CLIENT_MSG_MOVE_CHESS) {
            printf("输入坐标:");
            scanf("%d,%d", &x, &y);
        }
        mesg.cli_msg = (enum ClientMessageType)choice_cli;
        mesg.srv_msg = (enum ServerMessageType)choice_srv;
        mesg.color   = 1;
        mesg.coord_x = x;
        mesg.coord_y = y;
        memset(buffer, 0, sizeof(buffer));
        memcpy(buffer, &mesg, sizeof(message_t));
        send(cli_fd, &buffer, sizeof(message_t), 0);
    }

    close(cli_fd);

    return 0;
}
